Imports System.Runtime.InteropServices
Imports System.Threading

Public Class fStartup

    <DllImport("gdi32")> _
    Public Shared Function AddFontResource(ByVal lpFileName As String) As Integer
    End Function

    <DllImport("kernel32.dll", SetLastError:=True)> _
    Shared Function WriteProfileString(ByVal lpszSection As String, ByVal lpszKeyName As String, ByVal lpszString As String) As Integer
    End Function

    <DllImport("user32.dll")> _
    Public Shared Function SendMessage(ByVal hWnd As Integer, ByVal Msg As UInteger, ByVal wParam As Integer, ByVal lParam As Integer) As Integer
    End Function

    Private CheckState As Boolean

    Private objStateLock As New Object

    Private isServerUp As Boolean
    Private ServerUserCount As Integer

    Private strserver As String = "localhost"

    Private isCorrectVersion As Boolean = False
    Private server_required_clientversionstring As String

    Private isWaiting As Boolean = False

    Private statethread As System.Threading.Thread

    Private Sub ServerStatusUpdate()

        Try

            isWaiting = True

            Dim url As String
            Dim data As System.IO.Stream


            Dim webclient As New System.Net.WebClient()

            SyncLock objStateLock
                url = "http://" & strserver & "/?q=usercount"
            End SyncLock

            data = webclient.OpenRead(url)

            If CheckState Then

                SyncLock objStateLock
                    Dim reader As System.IO.StreamReader = New System.IO.StreamReader(data)

                    Dim count As String = reader.ReadToEnd()
                    reader.Close()

                    Debug.Print("HTTP Returned Usercount: '" & count & "'")
                    ServerUserCount = CInt(count)
                    isServerUp = True

                    SyncLock objStateLock
                        url = "http://" & strserver & "/?q=clientversion"
                    End SyncLock

                    data = webclient.OpenRead(url)

                    SyncLock objStateLock

                        reader = New System.IO.StreamReader(data)
                        server_required_clientversionstring = reader.ReadToEnd()
                        reader.Close()

                        If server_required_clientversionstring = Globals.ClientVersion Then
                            isCorrectVersion = True
                            isWaiting = False
                        Else
                            isCorrectVersion = False
                            isWaiting = False
                        End If

                    End SyncLock

                End SyncLock

            End If

        Catch ex As System.Net.WebException
            isServerUp = False
            isWaiting = False

        Catch ex As ArgumentException
            isServerUp = False
            isWaiting = False

        Catch ex As ThreadAbortException

            Exit Sub

        End Try

    End Sub

    Private Sub fStartup_FormClosing(sender As Object, e As FormClosingEventArgs) Handles Me.FormClosing

        If CheckState Then
            e.Cancel = True
            CheckState = False
        Else
            Application.Exit()
        End If

    End Sub

    'main entry point for the application
    Private Sub fStartup_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

        Globals.Init(Me)

        InstallProFontWin()

        CheckState = True

        PopulateServers()
        PopulateResoloutions()
        Application.DoEvents()

        'statethread = New Threading.Thread(AddressOf ServerStatusUpdater)
        'statethread.Start()

        Me.BringToFront()
        Me.WindowState = FormWindowState.Normal
        Me.Text = "MirEvo Launcher - Client Version: " & Globals.ClientVersion

        'UpdateColor()

    End Sub

    Private Sub PopulateResoloutions()

        cmbResoloution.BeginUpdate()
        cmbResoloution.Items.Clear()

        For i As Integer = 0 To Globals.ResoloutionCount - 1

            cmbResoloution.Items.Add(Globals.aResouloutionX(i) & " x " & Globals.aResouloutionY(i))

        Next

        cmbResoloution.EndUpdate()

        cmbResoloution.SelectedIndex = Globals.iniConfig.GetInteger("RES", "SELECTED", 0)

    End Sub

    Private Sub UpdateColor()
        If isWaiting Then
            cmbServer.BackColor = Color.Silver
            lblUsers.ForeColor = Color.Black
            lblUsers.Text = "Checking server state..."
        Else
            If isServerUp Then
                If isCorrectVersion Then
                    cmbServer.BackColor = Color.Green
                    lblUsers.ForeColor = Color.Green
                    lblUsers.Text = "User Count: " & ServerUserCount
                Else
                    cmbServer.BackColor = Color.Orange
                    lblUsers.ForeColor = Color.Orange
                    lblUsers.Text = "SERVER REQUIRES :" & vbCrLf & server_required_clientversionstring
                End If
            Else
                cmbServer.BackColor = Color.Red
                lblUsers.ForeColor = Color.Red
                lblUsers.Text = "   server appears to " & vbCrLf & _
                                "   be offline!"
            End If
        End If

    End Sub

    Private Sub InstallProFontWin()

        Dim Ret As Integer
        Dim Res As Integer
        Dim FontPath As String
        Const WM_FONTCHANGE As Integer = &H1D
        Const HWND_BROADCAST As Integer = &HFFFF
        FontPath = Globals.sRootPath & "Font\ProFontWindows.ttf"
        Dim FontsDirPath As String = Environment.GetEnvironmentVariable("windir") & "\Fonts\ProFontWindows.ttf"

        Try
            Microsoft.VisualBasic.FileCopy(FontPath, FontsDirPath)
            Ret = AddFontResource(FontsDirPath)
            Res = SendMessage(HWND_BROADCAST, WM_FONTCHANGE, 0, 0)
            Ret = WriteProfileString("fonts", "ProFontWindows (TrueType)", "ProFontWindows.ttf")
        Catch
        End Try

    End Sub

    'populates the server list with the details stored
    Private Sub PopulateServers()

        cmbServer.Items.Clear()

        Dim count As Integer = Globals.iniConfig.GetInteger("SERVERS", "SERVERCOUNT", 0)

        If count > 0 Then

            Dim name As String, ip As String, port As Integer

            cmbServer.BeginUpdate()

            For i As Integer = 1 To count

                name = Globals.iniConfig.GetString("SERVERS", "SERVERNAME" & i.ToString, "")
                ip = Globals.iniConfig.GetString("SERVERS", "SERVERIP" & i.ToString, "")
                port = Globals.iniConfig.GetInteger("SERVERS", "SERVERPORT" & i.ToString, 0)

                cmbServer.Items.Add("[" & i.ToString & "] " & name & " (" & ip & ":" & port.ToString & ")")

            Next

            cmbServer.EndUpdate()

            cmbServer.SelectedIndex = Globals.iniConfig.GetInteger("SERVERS", "SERVERSELECTED", 0)

        Else

            MsgBox("No servers are currently on your list, you must add one to continue!", MsgBoxStyle.Exclamation, "MirEvoClient")
            AddServer()

        End If

    End Sub

    'adds a server to the list
    Private Sub AddServer()

        'local temp variables
        Dim name As String, ip As String, port As Integer



        'NAME
        name = InputBox("Server Name:", "MirEvoClient")
        If name.Length = 0 Then Exit Sub



        'DNS/IP Address
        ip = InputBox("Server IP:", "MirEvoClient")
        If ip.Length = 0 Then Exit Sub



        'PORT #
        Try
            port = CInt(InputBox("Server Port (Valid: 1-65535):", "MirEvoClient", "11100"))
        Catch
            port = 0
        End Try
        If Not (port >= 1 And port <= 65535) Then Exit Sub



        'WRITE SERVER TO FILE
        Dim count As Integer = Globals.iniConfig.GetInteger("SERVERS", "SERVERCOUNT", 0)

        count += 1

        Globals.iniConfig.WriteString("SERVERS", "SERVERNAME" & count.ToString, name)
        Globals.iniConfig.WriteString("SERVERS", "SERVERIP" & count.ToString, ip)
        Globals.iniConfig.WriteInteger("SERVERS", "SERVERPORT" & count.ToString, port)
        Globals.iniConfig.WriteInteger("SERVERS", "SERVERCOUNT", count.ToString)

        PopulateServers()

    End Sub

    Private Sub btnAdd_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAdd.Click

        AddServer()

    End Sub

    Private Sub btnCancel_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnCancel.Click

        If MsgBox("Are you sure you want to exit MirEvolution?", MsgBoxStyle.Question Or MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then

            CheckState = False
            Application.DoEvents()
            Application.Exit()

            End

        End If

    End Sub

    Private Sub btnConnect_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnConnect.Click

        CheckState = False

        Globals.iniConfig.WriteInteger("SERVERS", "SERVERSELECTED", cmbServer.SelectedIndex)

        Globals.iniConfig.WriteInteger("RES", "X", Globals.aResouloutionX(cmbResoloution.SelectedIndex))
        Globals.iniConfig.WriteInteger("RES", "Y", Globals.aResouloutionY(cmbResoloution.SelectedIndex))
        Globals.iniConfig.WriteInteger("RES", "SELECTED", cmbResoloution.SelectedIndex)

        Dim MirEvoExePath As String = Globals.sRootPath & Constants.GameExe & " -rungame"
        Shell(MirEvoExePath, AppWinStyle.NormalFocus, False)

        Me.Close()
        Application.Exit()
        Environment.Exit(0)

    End Sub

    Private threadServerState As Thread

    Private Sub cmbServer_SelectedIndexChanged(sender As Object, e As EventArgs) Handles cmbServer.SelectedIndexChanged
        If CheckState Then
            strserver = Globals.iniConfig.GetString("SERVERS", "SERVERIP" & (cmbServer.SelectedIndex + 1).ToString, "localhost")
            Debug.Print(strserver)

            If Not threadServerState Is Nothing Then
                If threadServerState.ThreadState = ThreadState.Running Then
                    threadServerState.Abort()
                End If
            End If

            threadServerState = New Thread(AddressOf ServerStatusUpdate)
            threadServerState.Start()
        End If

    End Sub

    Private Sub CheckErrorReport()

        Dim file As String = Globals.sRootPath & Constants.ErrorFile

        If FileIO.FileSystem.FileExists(file) Then

            Dim stream As System.IO.StreamReader = FileIO.FileSystem.OpenTextFileReader(file)
            Dim line As String

            'Try

            'load info from error.txt
            line = stream.ReadLine()
            'date time of this error report
            Dim p As Integer = InStr(line, "|")
            Dim sDT As String = Strings.Left(line, p - 1)
            'ip of server
            line = Strings.Right(line, line.Length - p)
            p = InStr(line, "|")
            Dim sIP As String = Strings.Left(line, p - 1)

            Dim lDT As String = Globals.iniConfig.GetString("ERROR", "LASTREPORT", "")

            If lDT = "" Then lDT = "01/01/2013 00:00:00"

            If (System.DateTime.Parse(lDT) < System.DateTime.Parse(sDT)) Then
                'submit error

                If MsgBox("Report last error?", MessageBoxButtons.YesNo) = MsgBoxResult.Yes Then

                    'url to upload to
                    Dim err_report_url As String = "http://www.lom3.co.uk/ul.php"
                    'web client
                    Dim webclient As New System.Net.WebClient()

                    'upload
                    webclient.UploadFile(err_report_url, file)

                    'wait then dispose web client
                    Application.DoEvents()
                    webclient.Dispose()

                    'delete error.txt file
                    FileIO.FileSystem.DeleteFile(file)

                    'write last report to ini
                    Globals.iniConfig.WriteString("ERROR", "LASTREPORT", sDT)

                End If

                'Catch ex As Exception

                'End Try

            End If

            stream.Close()

        End If

    End Sub

    Private Sub fStartup_Shown(sender As Object, e As EventArgs) Handles Me.Shown
        CheckErrorReport()
    End Sub

    Private Sub btnReset_Click(sender As Object, e As EventArgs) Handles btnReset.Click

        If MsgBox("Reset config file?", MsgBoxStyle.Question Or MsgBoxStyle.YesNo) = MsgBoxResult.Yes Then

            If FileIO.FileSystem.FileExists(Globals.sRootPath & Constants.EvoConfigIni) Then

                FileIO.FileSystem.DeleteFile(Globals.sRootPath & Constants.EvoConfigIni)

            End If

            FileIO.FileSystem.CopyFile(Globals.sRootPath & Constants.PatchConfigIni, Globals.sRootPath & Constants.EvoConfigIni)

            PopulateServers()
            PopulateResoloutions()
            Application.DoEvents()

            MsgBox("Config replaced with default!")

        End If

    End Sub

    Private Sub tmrState_Tick(sender As Object, e As EventArgs) Handles tmrState.Tick
        UpdateColor()
    End Sub
End Class
